<template>
  	<div class="app-container">

		<div class="filter-container">
			<el-input  style="width: 200px;"  v-model="query.name" placeholder="姓名" class="filter-item"  ></el-input>
			<el-input  style="width: 200px;"  v-model="query.phone" placeholder="电话" class="filter-item"  ></el-input>
			<el-button @click="queryRecords" type="primary" class="filter-item">查询</el-button>
      <el-button @click="getRecords" type="danger" class="filter-item">刷新</el-button>
      <el-button @click="openAddDialog" type="primary" class="filter-item">添加</el-button>
		</div>

		<el-table
		v-loading="listLoading"
		:data="list"
		element-loading-text="Loading"
		border
		fit
		highlight-current-row
    v-horizontal-scroll="'always'"
		>
<!--			<el-table-column type="selection" width="55" />-->
<!--			<el-table-column type="index" label="序列" width="50" />-->
			<el-table-column prop="id" label="ID" min-width="50" />
            <el-table-column prop="avatar" label="头像" min-width="80" >
                <template slot-scope="scope">
                    <img v-if="scope.row.avatar" class="table-img" :src="host+scope.row.avatar">
                </template>
            </el-table-column>
			<el-table-column prop="name" label="用户名" min-width="120" />
			<el-table-column prop="real_name" label="真实姓名" min-width="120" />
			<el-table-column prop="phone" label="电话" min-width="120" />
			<el-table-column prop="email" label="邮箱" min-width="200" />
			<el-table-column show-overflow-tooltip prop="beizhu" label="备注" min-width="300" />
			<el-table-column prop="created_at" label="创建时间" min-width="160" />
			<el-table-column prop="is_available" label="是否有效" min-width="100" >
                <template slot-scope="scope">
                    <el-switch
                    v-model="scope.row.status"
                    active-color="#409EFF"
                    inactive-color="#909399"
                    :active-value="1"
                    :inactive-value="2"
                    @change="changeSwitch(scope.row)">
                    </el-switch>
                </template>

            </el-table-column>
			<el-table-column fixed="right" label="操作" min-width="150">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.name!='SuperAdmin'" size="mini" type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                  <el-button v-if="scope.row.name!='SuperAdmin'" size="mini" type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                  <el-button size="mini" type="text" @click="coverPassword(scope.row.id)">重置密码</el-button>
                </template>
			</el-table-column>
		</el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.page"
        :page-sizes="[10, 20, 100, 200]"
        :page-size="pagination.pageSize"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total">
      </el-pagination>

        <!-- 添加用户 -->
		<el-dialog :title="isAdd?'添加用户':'编辑用户'"  :visible.sync="addDialogFormVisible">
			<el-form ref="form" :model="form" label-width="80px" :rules="rules"  v-loading="formLoading" >
				<el-form-item label="头像" prop="avatar">
          <el-upload
              accept=".png,.jpg,.jpeg"
              class="avatar-uploader"
              :action="host+'/guard/upload?module=guardUser'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="urlAvatar" :src="urlAvatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
				</el-form-item>

        <el-form-item label="是否激活" prop="is_available">
          <el-switch
            :active-value="1"
            :inactive-value="2"
            v-model="form.status"
            active-text="是"
            inactive-text="否">
          </el-switch>
				</el-form-item>

				<el-form-item label="用户名" prop="name">
					<el-input v-model="form.name"></el-input>
				</el-form-item>
				<el-form-item label="真实姓名" prop="real_name" >
					<el-input v-model="form.real_name"></el-input>
				</el-form-item>
				<el-form-item v-if="isAdd" label="密码" prop="password" >
					<el-input type="password" v-model="form.password"></el-input>
				</el-form-item>
				<el-form-item v-if="isAdd"  label="确认密码" prop="repassword" >
					<el-input type="password" v-model="form.repassword"></el-input>
				</el-form-item>
				<el-form-item label="电话" prop="phone">
					<el-input  v-model="form.phone"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input  type="email" v-model="form.email"></el-input>
				</el-form-item>
				<el-form-item label="角色" prop="selectRoleIds">
          <el-select v-model="form.selectRoleIds" multiple placeholder="请选择">
              <el-option
                  v-for="item in roles"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
          </el-select>
				</el-form-item>
				<el-form-item label="备注">
					<el-input :rows="3" type="textarea" v-model="form.beizhu"></el-input>
				</el-form-item>
				<el-form-item v-if="isAdd" >
					<el-button type="primary" @click="onSubmit('form')">立即创建</el-button>
					<el-button>重置</el-button>
				</el-form-item>
				<el-form-item v-else >
					<el-button type="primary" @click="onSubmit('form')">修改</el-button>
				</el-form-item>
			</el-form>
	    </el-dialog>
  </div>
</template>

<script>

import { myGet, myPost } from '@/utils/myUtils'

const urlUserLst = '/guard/rbac/guardUser/lst';
const urlUserEdit = '/guard/rbac/guardUser/edit';
const urlAddUser = '/guard/rbac/guardUser/add';
const urlGetUser = '/guard/rbac/guardUser/getUser';
const urlDeleteUser = '/guard/rbac/guardUser/del';
const urlCoverPassword  = '/guard/rbac/guardUser/coverPassword';
const urlRole = '/guard/rbac/role/lst'

export default {

    data() {

        let checkPhone = (rule, value, callback)=>{
            const reg =/^[1][3-9][0-9]{9}$/;
            if(value==''||value==undefined||value==null){
                callback();
            }else {
                if ((!reg.test(value)) && value != '') {
                    callback(new Error('请输入正确的电话号码'));
                } else {
                    callback();
                }
            }
        };

        let reg = /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]{6,12}$/
        var validateNewPwd = (rule, value, callback) => {
            if (!reg.test(value)) {
                callback(new Error('密码应是6-12位数字、字母或字符！'))
            } /*else if (this.form.oldPasswd === value) {
                callback(new Error('新密码与旧密码不可一致！'))
            } */else {
                callback()
            }
        }
        var validateComfirmPwd = (rule, value, callback) => {
            if (!reg.test(value)) {
                callback(new Error('密码应是6-12位数字、字母或字符！'))
            } else if (this.form.password !== value) {
                callback(new Error('确认密码与新密码不一致！'))
            } else {
                callback()
            }
        }

        return {
          host:process.env.VUE_APP_HOST,
          list: [],
          urlAvatar:'',
          isAdd:true,
          addDialogFormVisible:false,
          dialogFormVisible:false,
          formLoading:false,
          listLoading: true,
          roles:[],

          query:{
            name:'',
            phone:''
          },
          pagination:{
            page:1,
            pageSize:10,
            total:0,
          },
          form:{
            id:0,
            name: '',
            real_name: '',
            phone: '',
            email: '',
            beizhu: '',
            avatar: '',
            password:'',
            status:1,
            selectRoleIds:[],

          },
          rules: {
            name: [
                { required: true, message: '必填', trigger: 'blur' }
            ],
            real_name: [
                { required: true, min: 3, max:5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
            ],
            phone:[
                { required: true, message: '请输入手机', trigger: 'blur' },
                { validator: checkPhone, trigger: 'blur' }
            ],
            email:[
                { required: true, message: '请输入邮箱格式', trigger: 'blur' },
                { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
            ],
            selectRoleIds:[
                {required: true, type: 'array', message: '至少选择一个角色', trigger: ['change','blur']}
            ],
            password:[
                { required: true, message: '请输入新密码', trigger: 'blur' },
                { validator: validateNewPwd, trigger: 'blur' }
            ],
            repassword: [
                { required: true, message: '请输入确认密码', trigger: 'blur' },
                { validator: validateComfirmPwd, trigger: 'blur' }
            ]
          },
        }
    },

    methods: {

      coverPassword(id){

        this.$confirm('确定要重置密码吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          myPost(urlCoverPassword,{id}).then(res=>{
            if(res.status){
              this.$message.success(res.msg)
            }
          })
        }).catch(() => {

        });
      },

      reload(){
        Object.assign(this.$data.query,this.$options.data().query)
        Object.assign(this.$data.pagination,this.$options.data().pagination)
        this.getRecords()
      },

      queryRecords(){
        Object.assign(this.$data.pagination,this.$options.data().pagination)
        this.getRecords()
      },

      getRecords(){
        this.listLoading = true;
        const params = Object.assign(this.query,this.pagination)
        myGet(urlUserLst,params).then(res=>{
          this.listLoading = false;
          if(res.status){
            this.list = res.data.records
            this.pagination.total = res.data.total
          }
        })
      },
      changeSwitch(row){
        const id= row.id
        const status= row.status
        myGet(urlUserEdit,{id,status}).then(res=>{
          if(res.status){
            this.$message.success(res.msg)
          }
        })
      },

      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
              this.formLoading = true;
              myPost(urlAddUser,this.form).then(res=>{
                this.formLoading = false;
                this.addDialogFormVisible = false
                if(res.status){
                  Object.assign(this.form,this.$options.data().form)
                  this.$message.success(res.msg);
                  this.reload();
                }
              })
          } else {
              this.$message.error('验证失败！');
              return false;
          }
        });
      },
      openAddDialog(){
        myGet(urlRole).then((res)=>{
           this.roles = res.data.records
           this.addDialogFormVisible = true
       })
      },
      handleEdit(index, row) {
        this.isAdd = false
        this.listLoading = true;
        const id = row.id

        myGet(urlGetUser,{id}).then((res)=>{
          let user = res.data.records[0];
          const {avatar,id,name,email,phone,real_name,status,beizhu} = user
          Object.assign(this.form,{avatar,id,name,email,phone,real_name,status,beizhu})
          this.urlAvatar = (user.avatar=='' || user.avatar==null || user.avatar==undefined)?"":this.host+user.avatar
          if(user.role_ids.length>0){
            user.role_ids.split(',').forEach((item)=>{
              this.form.selectRoleIds.push(parseInt(item))
            })
          }

          this.openAddDialog();
          this.listLoading = false;
         })
      },
        handleDelete(index, row) {
          this.$confirm('确认删除吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let id = row.id
            myGet(urlDeleteUser,{id}).then(res=>{
              if(res.status){
                this.$message.success(res.data.msg);
                this.reload();
              }
            })
          })
        },

      handleSizeChange(val) {
        this.pagination.pageSize = val
        this.pagination.page = 1
        this.getRecords()
      },
      handleCurrentChange(val) {
        this.pagination.page  = val
        this.getRecords();
      },
      handleAvatarSuccess(res, file) {
        if(res.status){
            this.urlAvatar = res.data.records.url
            this.form.avatar = res.data.records.filePath
        }else{
            this.$message.error(res.msg)
        }
      },
        beforeAvatarUpload(file) {
          const isLt2M = file.size / 1024 / 1024 < 2;
          if (!isLt2M) {
              this.$message.error('上传头像图片大小不能超过 2MB!');
          }
          return isLt2M;
        },

        toggleSelection(rows) {
          if (rows) {
          rows.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row);
          });
          } else {
              this.$refs.multipleTable.clearSelection();
          }
        }
    },
    mounted() {
        this.getRecords()
    }
}
</script>

<style>

.table-img{
    width: 50px;
    height: 50px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}
.avatar {
    width: 100px;
    height: 100px;
    display: block;
}
</style>


